package com.ChatServer.ferradm.cs.newpaltz.edu;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class ChatServerInit extends PreferenceActivity implements OnSharedPreferenceChangeListener {
	
	/**Initialize the variables */
	SharedPreferences prefManager;
	SharedPreferences   defaultManager;
	Editor edit;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.chatpreferencescreen);
		defaultManager=PreferenceManager.getDefaultSharedPreferences(this);
		edit=defaultManager.edit();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		prefManager = getPreferenceManager().getSharedPreferences();
		prefManager.registerOnSharedPreferenceChangeListener(this);
		/**Everytime I do onStart if the custimizeConnection is not checked I call initialize*/
		if (!defaultManager.getBoolean("custumizeConnection", false)){
			initialize();
		}
	
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreference, String key) {
		if(key!=null && sharedPreference!=null){
			/**If I uncheck the custimizeConnection, I call initialize*/
			if (key.equals("custumizeConnection") && !sharedPreference.getBoolean(key, false)){
				initialize();
			}else
				if(key.equals("custumizeConnection")&& sharedPreference.getBoolean(key, false)){
					Toast.makeText(this, "You are editing the connection setting at your own risk !", Toast.LENGTH_SHORT).show();
				}
				else{
					//DEBUG
					System.out.println( key+" : "+sharedPreference.getString(key, "").toString());
		}
		}
		
		
	}
	/** Method that get the IP set it and set the default port*/
	public void initialize(){
		 	Log.i("initialize", "Starting OK");
			ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
			 Log.i("initialize", "connectivityManager OK");
			NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
			Log.i("initialize", "networkInfo OK");	
			if (networkInfo!=null){
			String networkType=networkInfo.getTypeName();
			Log.i("initialize", "networkType OK");	
			State networkState=networkInfo.getState();
			Log.i("initialize", "getState OK");			
			if (networkState.compareTo(State.CONNECTED)==0){
			edit.putString("lsPort", Integer.toString(getResources().getInteger(R.integer.lsPort)));
			edit.putString("serverPort",Integer.toString(getResources().getInteger(R.integer.clientPort)));
			String ip=getLocalIpAddress();			
			edit.putString("lsHost", ip);
			edit.putString("serverHost", ip);
			edit.commit();
				
			}
			}else{
				Toast.makeText(this,"Unable to determine IP " , Toast.LENGTH_LONG).show();
			}
			
		
	}
	
	/**Return the IP adress*/
	 public String getLocalIpAddress() {
	        try {
	            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
	                NetworkInterface intf = en.nextElement();
	                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
	                    InetAddress inetAddress = enumIpAddr.nextElement();
	                    if (!inetAddress.isLoopbackAddress()) {
	                        return (inetAddress.getHostAddress().toString());
	                    }
	                }
	            }
	           
	        } catch (SocketException ex) {
	            Log.e( "SocketException", ex.toString());
	        }
	        return null;
	    }

/**Add a menu to go to the chatWindow*/
	 @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1000, 0, "Validate and connect").setIcon(android.R.drawable.ic_menu_save);
		return super.onCreateOptionsMenu(menu);
	    }
	    @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	    	if (item.getItemId()==1000 ){
	    		Intent intent=new Intent(this,ChatServerWindow.class);
	    		this.startActivity(intent);
	    		finish();
	    	} 
	    	return super.onOptionsItemSelected(item);
	    }

}
